﻿using System;
using System.Data;
using System.ServiceModel;
using System.Windows.Forms;
using System.ComponentModel;
using Infragistics.Win.UltraWinGrid;

namespace DMSClient
{
    public partial class RegionUser : Form
    {
        private DataTable dt;
        private string ambient;
        private WSHttpBinding Binding;
        private EndpointAddress address;

        public RegionUser()
        {
            Binding = new WSHttpBinding();
            Binding.MaxReceivedMessageSize = Int32.MaxValue;
            Binding.MaxBufferPoolSize = Int32.MaxValue;
            Binding.CloseTimeout = TimeSpan.MaxValue;
            Binding.ReceiveTimeout = TimeSpan.MaxValue;
            Binding.SendTimeout = TimeSpan.MaxValue;
            Binding.Security.Mode = SecurityMode.None;
            Binding.ReaderQuotas.MaxStringContentLength = Int32.MaxValue;

            address = new EndpointAddress(Properties.Settings.Default.Server);

            this.ambient = Properties.Settings.Default.CurrentEnv;

            DMSServices.DMSServicesClient client = new DMSServices.DMSServicesClient(Binding, address);
            string respuesta = null;
            try
            {
                client.Open();
                respuesta = client.getDistributorsList(this.ambient);
                client.Close();
            }
            catch (Exception ex)
            {
                throw new Exception(Properties.Settings.Default.DistributorsListErrorMsg, ex.InnerException);
            }
            if (respuesta == null)
            {
                throw new Exception(Properties.Settings.Default.DistributorsNullListErrorMsg);
            }

            InitializeComponent();
            this.Text = Properties.Settings.Default.CurrentEnvDes + " - RegionUser Report";
            
            uceDistributors.DisplayMember = "cdOrgUnit";
            uceDistributors.ValueMember = "idOrgUnit";

            dt = new DataTable("dtDistributorsList");
            dt.Columns.Add("idOrgUnit", Type.GetType("System.Int16"));
            dt.Columns.Add("cdOrgUnit", Type.GetType("System.String"));

            DataSet dataSet = new DataSet();
            dataSet.Tables.Add(dt);
            System.IO.StringReader xmlSR = new System.IO.StringReader(respuesta);
            dataSet.ReadXml(xmlSR, XmlReadMode.ReadSchema);
            xmlSR.Close();

            uceDistributors.DataSource = dt;
            uceDistributors.SelectedIndex = 0;
        }

        private void RegionUser_Shown(object sender, EventArgs e)
        {
            loader.Left = (this.Width - loader.Width) / 2;
            loader.Top = ((this.Height - loader.Height) / 2) - loader.Height;
        }

        private void RegionUser_Resize(object sender, EventArgs e)
        {
            loader.Left = (this.Width - loader.Width) / 2;
            loader.Top = ((this.Height - loader.Height) / 2) - loader.Height;
        }

        private void ubSearch_Click(object sender, EventArgs e)
        {
            activarControles(false);
            bgwSearch.RunWorkerAsync();
        }

        private void bgwSearch_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
            DMSServices.DMSServicesClient client = new DMSServices.DMSServicesClient(Binding, address);
            string respuesta = null;
            try
            {
                client.Open();
                respuesta = client.getRegionUserReport(ambient, uceDistributors.Value.ToString());
                client.Close();
                if (worker.CancellationPending)
                {
                    e.Cancel = true;
                    return;
                }
            }
            catch (Exception ex)
            {
                throw new Exception(Properties.Settings.Default.ReportErrorMsg, ex.InnerException);
            }
            if (respuesta == null)
            {
                throw new Exception(Properties.Settings.Default.ReportNullErrorMsg);
            }

            dt = new DataTable("dtRegionUser");
            dt.Columns.Add("cdRegion", Type.GetType("System.String"));
            dt.Columns.Add("cdRegionType", Type.GetType("System.String"));
            dt.Columns.Add("dsRegion", Type.GetType("System.String"));
            dt.Columns.Add("cdRegionStatus", Type.GetType("System.String"));
            dt.Columns.Add("cdParentRegion", Type.GetType("System.String"));
            dt.Columns.Add("cdUser", Type.GetType("System.String"));
            dt.Columns.Add("nmFirstName", Type.GetType("System.String"));
            dt.Columns.Add("nmLastName", Type.GetType("System.String"));
            dt.Columns.Add("nrPhone1", Type.GetType("System.String"));
            dt.Columns.Add("nrPhone2", Type.GetType("System.String"));
            dt.Columns.Add("Email", Type.GetType("System.String"));
            dt.Columns.Add("cdUserStatus", Type.GetType("System.String"));

            DataSet dataSet = new DataSet("dsRegionUser");
            dataSet.Tables.Add(dt);
            System.IO.StringReader xmlSR = new System.IO.StringReader(respuesta);
            dataSet.ReadXml(xmlSR, XmlReadMode.ReadSchema);
            xmlSR.Close();
        }

        private void bgwSearch_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                if (!this.IsDisposed)
                {
                    this.BringToFront();
                    MessageBox.Show(this, e.Error.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    activarControles(true);
                }
            }
            else if (!e.Cancelled && !this.IsDisposed)
            {
                ugRegionUser.DataSource = dt;
                activarControles(true);
            }
        }

        private void activarControles(bool value)
        {
            loader.Visible = !value;
            ultraGroupBox2.Enabled = value;
            ugRegionUser.Enabled = value;
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            if (ugRegionUser.Rows.Count < 1)
            {
                MessageBox.Show(this, "There is no data to export", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
            System.Windows.Forms.SaveFileDialog dialogo = new System.Windows.Forms.SaveFileDialog();
            dialogo.DefaultExt = "xls";
            Infragistics.Win.UltraWinGrid.ExcelExport.UltraGridExcelExporter Exporter = new Infragistics.Win.UltraWinGrid.ExcelExport.UltraGridExcelExporter();
            if (dialogo.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                Exporter.Export(ugRegionUser, dialogo.FileName);
                if (MessageBox.Show(this, "Do you want o open the file?", this.Text, MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    System.Diagnostics.Process.Start(dialogo.FileName);
                }
            }
        }

        private void uceDistributors_ValueChanged(object sender, EventArgs e)
        {
            ugRegionUser.DataSource = null;
        }

        private void RegionUser_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (bgwSearch.IsBusy)
            {
                bgwSearch.CancelAsync();
            }
        }

        private void RegionUser_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)27)
            {
                this.Close();
            }
        }

        private void ugRegionUser_InitializeLayout(object sender, Infragistics.Win.UltraWinGrid.InitializeLayoutEventArgs e)
        {
            foreach (UltraGridBand bands in e.Layout.Bands)
            {
                foreach (UltraGridColumn ugc in bands.Columns)
                {
                    ugc.PerformAutoResize(PerformAutoSizeType.AllRowsInBand, true);
                }
            }
        }
    }
}